package demo1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectClassDemo {
    public static void reflectNewInstance() throws Exception{
        Class<?> c1 = Class.forName("demo1.Student");
        Student student =(Student) c1.newInstance();
        System.out.println(student);
    }
    public static void reflectPrivateConstructor() throws Exception{
        Class<?> c1 = Class.forName("demo1.Student");
        Constructor<?> constructor = c1.getDeclaredConstructor(String.class, int.class);
        constructor.setAccessible(true);
        Student student = (Student) constructor.newInstance("xiaoming", 12);
        System.out.println(student);
    }

    public static void reflectPrivateField() throws Exception {
        Class<?> c1 = Class.forName("demo1.Student");
        Student student = (Student)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);
        name.set(student, "zhan");
        System.out.println(student);
    }

    public static void reflectPrivateMethod() throws Exception {
        Class<?> c1 = Class.forName("demo1.Student");
        Student student = (Student)c1.newInstance();
        Method function = c1.getDeclaredMethod("function", String.class);
        function.setAccessible(true);
        function.invoke(student, "nihao");
    }
    public static void main(String[] args) throws Exception{
//        reflectNewInstance();
//        reflectPrivateConstructor();
//        reflectPrivateField();
        reflectPrivateMethod();
    }
}
